package logic

import (
	"cmdservice/dataconfig"
	"context"
	"gitee.com/jmdvirus/jkgo/jk/jklog"
	"io/ioutil"
	"os/exec"

	"cmdservice/internal/svc"
	"cmdservice/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CmdPositionGetServiceLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCmdPositionGetServiceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CmdPositionGetServiceLogic {
	return &CmdPositionGetServiceLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CmdPositionGetServiceLogic) CmdPositionGetService(req *types.Request) (resp *types.Response, err error) {
	jklog.L().Infoln("cmd position get name:", req.Name)
	data := dataconfig.CmdDataListGet()

	cmd := exec.Command(data.Cmd, data.Args, req.Name)

	stdout, err := cmd.StdoutPipe()
	if err != nil { //获取输出对象，可以从该对象中读取输出结果
		jklog.L().Errorln(err)
		return nil, err
	}
	defer stdout.Close() // 保证关闭输出流

	err = cmd.Start()
	if err != nil { // 运行命令
		jklog.L().Errorln(err)
		return nil, err
	}

	rsp := types.Response{}
	if opBytes, err := ioutil.ReadAll(stdout); err != nil { // 读取输出结果
		jklog.L().Errorln(err)
		return nil, err
	} else {
		jklog.L().Infoln(string(opBytes))
		rsp.Message = string(opBytes)
	}

	return &rsp, nil
}
